package com.xwj.controller.admin;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.github.pagehelper.PageInfo;
import com.google.gson.JsonObject;
import com.xwj.config.FileUploadCosConfig;
import com.xwj.data.StaticData;
import com.xwj.dto.RegisterUserDto;
import com.xwj.entity.PassWordEntity;
import com.xwj.entity.RaRegisterUser;
import com.xwj.service.Impl.RegisterUserServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.*;

@RestController
@RequestMapping("/admin/registerUser/")
public class RegisterUserController {

    @Autowired
    private RegisterUserServiceImpl registerUserService;
    @Autowired
    private FileUploadCosConfig fileUploadCos;


    @RequestMapping(value = "registerUserInfoList")
    public ModelAndView repairInfoList(ModelAndView modelAndView) {
        modelAndView.setViewName("/admin/registerUser/registerUser");
        return modelAndView;
    }

    /**
     * 显示或查询
     *
     * @param pageIndex
     * @param pageSize
     * @param key
     * @return
     */
    @RequestMapping(value = "registerUserInfoDetail", method = RequestMethod.POST)
    public Map<String, Object> repariInfoList(@RequestParam(value = "page") Integer pageIndex,
                                              @RequestParam(value = "limit") Integer pageSize,
                                              @RequestParam(value = "key", required = false) String key) {
        PageInfo<RaRegisterUser> page;
        RegisterUserDto registerUserDto = null;
        if (key != null) registerUserDto = JSON.parseObject(key, new TypeReference<RegisterUserDto>() {
        });
        if (registerUserDto == null)
            page = registerUserService.findAllUser(pageIndex, pageSize);
        else
            page = registerUserService.findUserByProperty(pageIndex, pageSize, registerUserDto);
        Map<String, Object> map = new HashMap<>();
        map.put("code", 0);
        map.put("msg", "");
        map.put("count", page.getTotal());
        map.put("data", page.getList());
        return map;
    }

    /**
     * 添加一个新用户
     *
     * @param json
     * @param request
     * @return
     */
    @RequestMapping(value = "addOneRegisterUser", method = RequestMethod.POST)
    public Map<String, Object> addOneRegisterUser(@RequestParam(value = "mydata") String json, HttpServletRequest request) {
        ServletContext context = request.getServletContext();
        String accountid = (String) context.getAttribute(StaticData.ADMIN_USER_LOGIN_ATTRIBUTE);
        RaRegisterUser raRegisterUser = JSON.parseObject(json, new TypeReference<RaRegisterUser>() {
        });
        Map<String, Object> map = new HashMap<>();
        if (registerUserService.findUserById(raRegisterUser.getId()) != null) {
            map.put("msg", "该账号已存在");
            return map;
        }
        if (registerUserService.findUserByMail(raRegisterUser.getMail()) != null) {
            map.put("msg", "该邮箱已经绑定一个账号，请换一个");
            return map;
        }
        if (registerUserService.findUserByPhone(raRegisterUser.getPhone()) != null) {
            map.put("msg", "该手机号码已经绑定一个账号，请换一个");
            return map;
        }
        raRegisterUser.setCreateTime(new DateTime().toString("yyyy-MM-dd HH:mm:ss"));
        String password;
        if (StringUtils.isBlank(raRegisterUser.getPassword()))
            password = raRegisterUser.getId(); //若没设密码，则默认与账号相同
        else
            password = raRegisterUser.getPassword();
        String slat = UUID.randomUUID().toString().substring(0, 8);
        String spwd = new Md5Hash(password, slat).toString();
        raRegisterUser.setPassword(spwd);
        raRegisterUser.setSalt(slat);
        String photo = registerUserService.getUrlformRedis(accountid + "_upload_registerUser_picture");
        if (StringUtils.isNotBlank(photo))
            raRegisterUser.setPhoto(photo);
        else
            raRegisterUser.setPhoto("/static/image/photo.jpg");
        if (registerUserService.addOneRegisterUser(raRegisterUser) > 0) {
            registerUserService.deleteFromRedis(accountid + "_upload_registerUser_picture");
            map.put("msg", "添加成功");
        } else
            map.put("msg", "添加失败");
        return map;
    }

    /**
     * 更新密码
     *
     * @param passWordEntity
     * @return
     */
    @RequestMapping(value = "updatePwd", method = RequestMethod.POST)
    public Map<String, Object> updatePwd(PassWordEntity passWordEntity) {
        Map<String, Object> map = new HashMap<>();
        PassWordEntity entity = registerUserService.getUserPassWord(passWordEntity.getId());
        String tmp = new Md5Hash(passWordEntity.getPassword(), entity.getSalt()).toString();
        if (StringUtils.isBlank(passWordEntity.getPassword())) {
            map.put("msg", "没做任何修改");
        } else if (tmp.equals(entity.getPassword())) {
            map.put("msg", "不可与旧密码相同");
        } else {
            if (registerUserService.updatePassword(passWordEntity) > 0)
                map.put("msg", "密码修改成功");
            else
                map.put("msg", "密码修改失败");
        }
        return map;
    }

    /**
     * 更新其他属性
     *
     * @param raRegisterUser
     * @return
     */
    @RequestMapping(value = "updateOtherProperty", method = RequestMethod.POST)
    public Map<String, Object> updateOtherProperty(RaRegisterUser raRegisterUser, HttpServletRequest request) {
        Map<String, Object> map = new HashMap<>();
        ServletContext context = request.getServletContext();
        String accountid = (String) context.getAttribute(StaticData.ADMIN_USER_LOGIN_ATTRIBUTE);
        String photo = registerUserService.getUrlformRedis(accountid + "_upload_registerUser_picture");
        if (StringUtils.isNotBlank(photo))
            raRegisterUser.setPhoto(photo);
        if (registerUserService.updateOtherProperty(raRegisterUser) > 0) {
            registerUserService.deleteFromRedis(accountid + "_upload_registerUser_picture");
            map.put("msg", "修改成功");
        } else
            map.put("msg", "修改失败");
        return map;
    }

    /**
     * 删除
     *
     * @param id
     * @return
     */
    @RequestMapping(value = "deleteById", method = RequestMethod.POST)
    public Map<String, Object> deleteById(@RequestParam(value = "id") String id) {
        Map<String, Object> map = new HashMap<>();
        List<String> ids = new ArrayList<>();
        ids.add(id);
        if (registerUserService.deleteByIds(ids) > 0)
            map.put("msg", "删除成功");
        else
            map.put("msg", "数据有误，删除失败");
        return map;
    }

    /**
     * 批量删除
     *
     * @param mydata
     * @return
     */
    @RequestMapping(value = "deleteBatchById", method = RequestMethod.POST)
    public Map<String, Object> deleteBatchById(@RequestParam(value = "mydata", required = false) String mydata) {
        Map<String, Object> map = new HashMap<>();
        List<RaRegisterUser> raRegisterUserList = JSON.parseArray(mydata, RaRegisterUser.class);
        if (raRegisterUserList.size() == 0) {
            map.put("msg", "未选中任何选项");
            return map;
        }
        List<String> ids = registerUserService.parseListId(raRegisterUserList);
        if (registerUserService.deleteByIds(ids) > 0)
            map.put("msg", "删除成功");
        else
            map.put("msg", "数据操作异常");
        return map;
    }

    /**
     * 照片上传
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "upload", method = RequestMethod.POST)
    public String handleFileUpload(HttpServletRequest request) {
        ServletContext context = request.getServletContext();
        String accountid = (String) context.getAttribute(StaticData.ADMIN_USER_LOGIN_ATTRIBUTE);
        String localPathDir = "/registerUserphoto";
        String localRealPathDir = request.getSession().getServletContext().getRealPath(localPathDir);
        File localSaveFile = new File(localRealPathDir);
        if (!localSaveFile.exists()) localSaveFile.mkdirs();
        String result = null;
        try {
            MultipartFile multipartFile = ((MultipartHttpServletRequest) request).getFile("file");
            String fileName = localRealPathDir + File.separator + multipartFile.getOriginalFilename();
            File file = new File(fileName);
            multipartFile.transferTo(file);
            result = fileUploadCos.uploadFile("/registerUserphoto/", fileName, multipartFile.getOriginalFilename());
            JSONObject jsonObject = JSON.parseObject(result);
            if (jsonObject.getInteger("code") == 0) {
                JsonObject jsonObject1 = new JsonObject();
                jsonObject1.addProperty("access_url", jsonObject.getJSONObject("data").getString("access_url"));
                registerUserService.addUrlToRedis(jsonObject1.toString(), accountid + "_upload_registerUser_picture");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }

}
